import 'package:hinge/common/models/topic_comment_model.dart';

class TopicModel {
  final int id;
  final String question;
  final double percentage;
  final List<TopicCommentModel> comments;

  TopicModel({
    required this.id,
    required this.question,
    required this.percentage,
    this.comments = const [],
  });

  // 从JSON构造
  factory TopicModel.fromJson(Map<String, dynamic> json) {
    List<TopicCommentModel> commentList = [];
    if (json['comments'] != null) {
      commentList =
          (json['comments'] as List)
              .map((comment) => TopicCommentModel.fromJson(comment))
              .toList();
    }

    return TopicModel(
      id: json['id'],
      question: json['question'],
      percentage: json['percentage'].toDouble(),
      comments: commentList,
    );
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'question': question,
      'percentage': percentage,
      'comments': comments.map((comment) => comment.toJson()).toList(),
    };
  }

  // 复制并修改话题对象
  TopicModel copyWith({
    int? id,
    String? question,
    double? percentage,
    List<TopicCommentModel>? comments,
  }) {
    return TopicModel(
      id: id ?? this.id,
      question: question ?? this.question,
      percentage: percentage ?? this.percentage,
      comments: comments ?? this.comments,
    );
  }
}
